package dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import pojo.Department;

import java.util.List;

/**
 * @author 郝雷蒙
 * @Description
 * @date 2020/12/8 17:10
 */
@Repository
public class DepartmentDaoImpl  implements DepartmentDao{
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public List<Department> selectAllDepartments(Integer start, Integer length) {
        RowMapper<Department> rowMapper = new BeanPropertyRowMapper<>(Department.class);

        List<Department> departments = jdbcTemplate.query("select d.did, d.dname, count(c.id) num from department as d\n" +
                "left join doctor as c on d.did = c.did\n" +
                        "group by d.did\n" +
                        "order by d.did limit ?,?",rowMapper,start,length);

        return departments;
    }

    @Override
    public Integer selectDepartmentCount() {
        return jdbcTemplate.queryForObject("select count(*) from department ",Integer.class);
    }

    @Override
    public Department selectDepartmentByid(Integer id) {

        RowMapper<Department> rowMapper = new BeanPropertyRowMapper<>(Department.class);

        return jdbcTemplate.queryForObject("select * from department where did = ? ",rowMapper,id) ;
    }

    @Override
    public Integer insertOneDepartment(Department department) {
        String sql = "insert into department(dname) values(?)";

        return jdbcTemplate.update(sql, department.getDname());
    }

    @Override
    public Integer updateOneDepartment(Department department) {
        String sql = "update department set dname = ? where did = ?";

        return jdbcTemplate.update(sql, department.getDname());
    }

    @Override
    public Integer deleteDepartmentByid(Integer id) {
        return jdbcTemplate.update("delete from department where did = ?", id);
    }
}
